import React, { useState, useEffect } from "react";
import {
  Card,
  Button,
  Alert,
  List,
  Badge,
  Space,
  Typography,
  Spin,
  Progress,
  Divider,
  Tag,
  Row,
  Col,
  message,
} from "antd";
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
  WifiOutlined,
  ApiOutlined,
  DatabaseOutlined,
  SecurityScanOutlined,
  CloudServerOutlined,
} from "@ant-design/icons";
import { authAPI, aiAPI, teacherAPI, studentAPI } from "../../services/api";
import { API_ENDPOINTS } from "../../config/env";

const { Title, Text, Paragraph } = Typography;

interface TestResult {
  name: string;
  status: "pending" | "success" | "error" | "warning";
  message: string;
  details?: string;
  duration?: number;
}

interface NetworkTestProps {
  onClose?: () => void;
}

const NetworkTest: React.FC<NetworkTestProps> = ({ onClose }) => {
  const [testing, setTesting] = useState(false);
  const [results, setResults] = useState<TestResult[]>([]);
  const [progress, setProgress] = useState(0);

  const tests = [
    {
      name: "基础网络连接",
      test: async () => {
        const start = Date.now();
        try {
          const response = await fetch("/api/v1/user/notify", {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
            },
          });
          const duration = Date.now() - start;

          if (response.ok) {
            return {
              status: "success" as const,
              message: "网络连接正常",
              details: `响应时间: ${duration}ms`,
              duration,
            };
          } else {
            return {
              status: "warning" as const,
              message: `HTTP ${response.status} ${response.statusText}`,
              details: "后端服务可能未启动或配置错误",
              duration,
            };
          }
        } catch (error: any) {
          const duration = Date.now() - start;
          return {
            status: "error" as const,
            message: "网络连接失败",
            details: error.message || "无法连接到后端服务器",
            duration,
          };
        }
      },
    },
    {
      name: "获取验证码接口",
      test: async () => {
        const start = Date.now();
        try {
          const response = await authAPI.getCaptcha();
          const duration = Date.now() - start;
          return {
            status: "success" as const,
            message: "验证码接口正常",
            details: `响应时间: ${duration}ms`,
            duration,
          };
        } catch (error: any) {
          const duration = Date.now() - start;
          return {
            status: "error" as const,
            message: "验证码接口失败",
            details: error.response?.data?.msg || error.message,
            duration,
          };
        }
      },
    },
    {
      name: "用户信息接口 (需要登录)",
      test: async () => {
        const start = Date.now();
        try {
          const response = await authAPI.getUserInfo();
          const duration = Date.now() - start;
          if (response?.code === 200) {
            return {
              status: "success" as const,
              message: "用户信息接口正常",
              details: `用户已登录，响应时间: ${duration}ms`,
              duration,
            };
          } else {
            return {
              status: "warning" as const,
              message: "需要先登录",
              details: response?.msg || "用户未登录或token已过期",
              duration,
            };
          }
        } catch (error: any) {
          const duration = Date.now() - start;
          if (error.response?.status === 401) {
            return {
              status: "warning" as const,
              message: "需要先登录",
              details: "用户未登录或token已过期",
              duration,
            };
          }
          return {
            status: "error" as const,
            message: "用户信息接口失败",
            details: error.response?.data?.msg || error.message,
            duration,
          };
        }
      },
    },
    {
      name: "教师班级列表接口",
      test: async () => {
        const start = Date.now();
        try {
          const response = await teacherAPI.getClasses();
          const duration = Date.now() - start;
          return {
            status: "success" as const,
            message: "教师接口正常",
            details: `响应时间: ${duration}ms`,
            duration,
          };
        } catch (error: any) {
          const duration = Date.now() - start;
          return {
            status: "error" as const,
            message: "教师接口失败",
            details: error.response?.data?.msg || error.message,
            duration,
          };
        }
      },
    },
    {
      name: "学生班级信息接口",
      test: async () => {
        const start = Date.now();
        try {
          const response = await fetch("/api/v1/stu/info?class_id=1");
          const duration = Date.now() - start;
          if (response.ok) {
            return {
              status: "success" as const,
              message: "学生接口正常",
              details: `响应时间: ${duration}ms`,
              duration,
            };
          } else {
            return {
              status: "warning" as const,
              message: `学生接口响应异常 (${response.status})`,
              details: "可能是参数问题或权限问题",
              duration,
            };
          }
        } catch (error: any) {
          const duration = Date.now() - start;
          return {
            status: "error" as const,
            message: "学生接口失败",
            details: error.message,
            duration,
          };
        }
      },
    },
    {
      name: "AI聊天接口",
      test: async () => {
        const start = Date.now();
        try {
          const response = await fetch("/api/v1/chat/message", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ message: "test" }),
          });
          const duration = Date.now() - start;
          if (response.ok) {
            return {
              status: "success" as const,
              message: "AI接口正常",
              details: `响应时间: ${duration}ms`,
              duration,
            };
          } else {
            return {
              status: "warning" as const,
              message: `AI接口响应异常 (${response.status})`,
              details: "可能是AI服务配置问题",
              duration,
            };
          }
        } catch (error: any) {
          const duration = Date.now() - start;
          return {
            status: "error" as const,
            message: "AI接口失败",
            details: error.message,
            duration,
          };
        }
      },
    },
  ];

  const runTests = async () => {
    setTesting(true);
    setResults([]);
    setProgress(0);

    for (let i = 0; i < tests.length; i++) {
      const test = tests[i];

      // 添加pending状态
      setResults((prev) => [
        ...prev,
        {
          name: test.name,
          status: "pending",
          message: "测试中...",
        },
      ]);

      try {
        const result = await test.test();

        // 更新测试结果
        setResults((prev) => {
          const newResults = [...prev];
          newResults[i] = {
            name: test.name,
            ...result,
          };
          return newResults;
        });
      } catch (error: any) {
        setResults((prev) => {
          const newResults = [...prev];
          newResults[i] = {
            name: test.name,
            status: "error",
            message: "测试异常",
            details: error.message,
          };
          return newResults;
        });
      }

      setProgress(((i + 1) / tests.length) * 100);

      // 添加短暂延迟，避免过快的请求
      await new Promise((resolve) => setTimeout(resolve, 500));
    }

    setTesting(false);
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "success":
        return <CheckCircleOutlined style={{ color: "#52c41a" }} />;
      case "error":
        return <CloseCircleOutlined style={{ color: "#ff4d4f" }} />;
      case "warning":
        return <SecurityScanOutlined style={{ color: "#faad14" }} />;
      case "pending":
        return <LoadingOutlined style={{ color: "#1890ff" }} />;
      default:
        return null;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "success":
        return "#52c41a";
      case "error":
        return "#ff4d4f";
      case "warning":
        return "#faad14";
      case "pending":
        return "#1890ff";
      default:
        return "#d9d9d9";
    }
  };

  const getSummary = () => {
    const total = results.length;
    const success = results.filter((r) => r.status === "success").length;
    const error = results.filter((r) => r.status === "error").length;
    const warning = results.filter((r) => r.status === "warning").length;

    return { total, success, error, warning };
  };

  const generateDiagnosticReport = () => {
    const summary = getSummary();
    const hasErrors = summary.error > 0;
    const hasWarnings = summary.warning > 0;

    let diagnosis = "";
    let suggestions: string[] = [];

    if (summary.success === summary.total) {
      diagnosis = "所有接口测试通过，网络连接正常！";
      suggestions.push("系统运行良好，可以正常使用。");
    } else if (hasErrors) {
      diagnosis = "发现网络连接问题，需要检查后端服务。";
      suggestions.push("1. 确认后端服务已启动 (http://localhost:8080)");
      suggestions.push("2. 检查防火墙设置和端口占用");
      suggestions.push("3. 查看后端日志确认服务状态");
      suggestions.push("4. 确认数据库连接正常");
    } else if (hasWarnings) {
      diagnosis = "部分接口存在问题，可能是权限或配置问题。";
      suggestions.push("1. 尝试重新登录获取有效token");
      suggestions.push("2. 检查用户权限配置");
      suggestions.push("3. 确认API参数格式正确");
    }

    return { diagnosis, suggestions };
  };

  useEffect(() => {
    // 组件加载时自动运行测试
    runTests();
  }, []);

  const summary = getSummary();
  const report = generateDiagnosticReport();

  return (
    <Card
      title={
        <Space>
          <WifiOutlined />
          网络连接诊断
        </Space>
      }
      extra={
        <Space>
          <Button onClick={runTests} loading={testing}>
            重新测试
          </Button>
          {onClose && <Button onClick={onClose}>关闭</Button>}
        </Space>
      }
      style={{ maxWidth: 800, margin: "0 auto" }}
    >
      {testing && (
        <div style={{ marginBottom: 24 }}>
          <Text>测试进度:</Text>
          <Progress percent={Math.round(progress)} status="active" />
        </div>
      )}

      {results.length > 0 && (
        <>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card size="small" style={{ textAlign: "center" }}>
                <Text>总测试数</Text>
                <div style={{ fontSize: 24, fontWeight: "bold" }}>
                  {summary.total}
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small" style={{ textAlign: "center" }}>
                <Text style={{ color: "#52c41a" }}>成功</Text>
                <div
                  style={{ fontSize: 24, fontWeight: "bold", color: "#52c41a" }}
                >
                  {summary.success}
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small" style={{ textAlign: "center" }}>
                <Text style={{ color: "#faad14" }}>警告</Text>
                <div
                  style={{ fontSize: 24, fontWeight: "bold", color: "#faad14" }}
                >
                  {summary.warning}
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small" style={{ textAlign: "center" }}>
                <Text style={{ color: "#ff4d4f" }}>错误</Text>
                <div
                  style={{ fontSize: 24, fontWeight: "bold", color: "#ff4d4f" }}
                >
                  {summary.error}
                </div>
              </Card>
            </Col>
          </Row>

          <Alert
            message={report.diagnosis}
            description={
              <div>
                {report.suggestions.map((suggestion, index) => (
                  <div key={index} style={{ marginBottom: 4 }}>
                    {suggestion}
                  </div>
                ))}
              </div>
            }
            type={
              summary.error > 0
                ? "error"
                : summary.warning > 0
                  ? "warning"
                  : "success"
            }
            showIcon
            style={{ marginBottom: 24 }}
          />

          <List
            dataSource={results}
            renderItem={(item) => (
              <List.Item>
                <List.Item.Meta
                  avatar={getStatusIcon(item.status)}
                  title={
                    <Space>
                      <Text strong>{item.name}</Text>
                      <Badge
                        status={
                          item.status === "success"
                            ? "success"
                            : item.status === "error"
                              ? "error"
                              : item.status === "warning"
                                ? "warning"
                                : "processing"
                        }
                      />
                      {item.duration && (
                        <Tag color="blue">{item.duration}ms</Tag>
                      )}
                    </Space>
                  }
                  description={
                    <div>
                      <div>{item.message}</div>
                      {item.details && (
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          {item.details}
                        </Text>
                      )}
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        </>
      )}

      <Divider />

      <div>
        <Title level={5}>
          <ApiOutlined /> API端点配置
        </Title>
        <Row gutter={[16, 8]}>
          <Col span={12}>
            <Text strong>用户认证:</Text> {API_ENDPOINTS.AUTH.LOGIN}
          </Col>
          <Col span={12}>
            <Text strong>教师接口:</Text> {API_ENDPOINTS.TEACHER.LIST_CLASS}
          </Col>
          <Col span={12}>
            <Text strong>学生接口:</Text> {API_ENDPOINTS.STUDENT.CLASS_INFO}
          </Col>
          <Col span={12}>
            <Text strong>AI聊天:</Text> {API_ENDPOINTS.AI.CHAT}
          </Col>
        </Row>
      </div>
    </Card>
  );
};

export default NetworkTest;
